﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
using ML.Utils;


namespace ML.Plug
{
    /// <summary>
    /// 微信帮助类(获取授权)
    /// </summary>
    public static class WechatHelper
    {
        private static readonly ILogger logger = new NLogLogger();
        /// <summary>
        /// 授权用户信息
        /// </summary>
        /// <param name="Code">授权Code</param>
        /// <returns></returns>
        public static JObject OAuth2UserInfo(string code)
        {
            try
            {
                //通过code换取网页授权access_token()
                string accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WechatConfig.appId + "&secret=" + WechatConfig.secret + "&code=" + code + "&grant_type=authorization_code";
                CS_OperaWeb ow = new CS_OperaWeb();
                string jsonAccessToken = ow.GetWebCode(accessTokenUrl, Encoding.UTF8);
                logger.Debug($"jsonAccessToken:{jsonAccessToken}");
                JObject jsonObj = (JObject)JsonConvert.DeserializeObject(jsonAccessToken);

                //拉取用户信息（如果网页授权作用域为snsapi_userinfo，则此时开发者可以通过access_token和openid拉取用户信息了)
                string strAccessToken = jsonObj["access_token"].ToString();
                string strOpenId = jsonObj["openid"].ToString();
                string userinfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + strAccessToken + "&openid=" + strOpenId;
                string strUserInfo = ow.GetWebCode(userinfoUrl, Encoding.UTF8);
                logger.Debug($"strUserInfo:{strUserInfo}");

                //处理用户信息并且返回
                JObject jsonObjUserInfo = (JObject)JsonConvert.DeserializeObject(strUserInfo);
                return jsonObjUserInfo;
            }
            catch (System.Exception exception)
            {
                logger.Info("授权用户信息失败："+exception.Message);
                return null;
            }
        }
    }
}